package com.jzy.secondhandbooktradingmanagement.controller;

import com.jzy.secondhandbooktradingmanagement.commom.Result;
import com.jzy.secondhandbooktradingmanagement.entity.Cart;
import com.jzy.secondhandbooktradingmanagement.service.ICartService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Resource
    ICartService cartService;

    @PostMapping
    public Result<?> save(@RequestBody Cart cart) {
        try {
            cartService.addToCart(cart);
            return Result.success();
        } catch (Exception e) {
            return Result.error("-1", e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        cartService.removeById(id);
        return Result.success();
    }

    @DeleteMapping("/empty")
    public Result<?> empty() {
        try {
            cartService.emptyCart();
            return Result.success();
        } catch (Exception e) {
            return Result.error("-1", e.getMessage());
        }
    }

    @GetMapping
    public Result<?> list() {
        try {
            List<Cart> carts = cartService.listCart();
            return Result.success(carts);
        } catch (Exception e) {
            return Result.error("-1", e.getMessage());
        }
    }
    
    @PutMapping
    public Result<?> update(@RequestBody Cart cart) {
        cartService.updateById(cart);
        return Result.success();
    }
}
